<template>
	<view>
		<view class="m30 flex-au" v-if="menuList.length > 0">
			<view v-for="(item, index) in menuList" :key="index" class="menu-item" @click="openUrl(item.path)">
				<view class="flex-au">
					<view class="icon radius30 pore" :style="{ 'backgroundColor': item.color }">
						<image :src="'../../static/images/contact/' + item.icon + '.png'" mode=""></image>
						<view class="count">
							<text class="f24 f-scale">{{ item.count < 99 ? item.count : '99+' }}</text>
						</view>
					</view>
				</view>
				<view class="c343 f26 mt10">{{ item.name }}</view>
			</view>
		</view>
		<scroll-view class="conversations" scroll-y="true">
			<view v-if="conversations.length > 0">
				<view class="scroll-item" v-for="(conversation, key) in conversations" :key="key">
					<view class="item-head">
						<image :src="api_host + conversation.data.avatar" class="head-icon"></image>
						<view class="item-head_unread" v-if="conversation.unread">{{ conversation.unread }}</view>
					</view>
					<view class="scroll-item_info" @click="chat(conversation)" @longpress="longPressDelete(conversation)">
						<view class="item-info-top">
							<text class="item-info-top_name">{{ conversation.data.name }}</text>
							<view class="item-info-top_time">{{ formatDate(conversation.lastMessage.timestamp) }}</view>
						</view>
						<view class="item-info-bottom">
							<view class="item-info-bottom-item">
								<view class="item-info-top_content" v-if="!conversation.lastMessage.recalled">
									<text class="unread-text">
										{{ conversation.lastMessage.read == false && conversation.lastMessage.senderId
											== currentUser.id ? '[未读]' : '' }}
									</text>

									<text v-if="conversation.lastMessage.senderId == currentUser.id">我: </text>
									<text v-else>{{ conversation.type == 'group' ?
										conversation.lastMessage.senderData.name : conversation.data.name }}:
									</text>
									<text v-if="conversation.lastMessage.type == 'text'">{{
										conversation.lastMessage.payload.text }}</text>
									<text v-else-if="conversation.lastMessage.type == 'video'">[视频消息]</text>
									<text v-else-if="conversation.lastMessage.type == 'audio'">[语音消息]</text>
									<text v-else-if="conversation.lastMessage.type == 'image'">[图片消息]</text>
									<text v-else-if="conversation.lastMessage.type == 'img'">[图片消息]</text>
									<text v-else-if="conversation.lastMessage.type == 'file'">[文件消息]</text>
									<text v-else-if="conversation.lastMessage.type == 'order'">[自定义消息:订单]</text>
									<text v-else-if="conversation.lastMessage.type == 'pet'">[宠物消息]</text>
									<text v-else>[未识别内容]</text>
								</view>
								<view class="item-info-top_content" v-else>

									<text v-if="conversation.lastMessage.senderId == currentUser.id">
										你撤回了一条消息
									</text>
									<view v-else>
										{{ conversation.type == 'group' ? conversation.lastMessage.senderData.name :
											conversation.data.name }}
										撤回了一条消息
									</view>
								</view>
								<view class="item-info-bottom_action" @click.stop="showAction(conversation)"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="no-conversation" v-else>当前没有会话</view>
			<view class="action-container" v-if="actionPopup.visible">
				<view class="layer" @click="actionPopup.visible = false"></view>
				<view class="action-box">
					<view class="action-item" @click="topConversation">
						{{ actionPopup.conversation.top ? '取消置顶' : '置顶聊天' }}
					</view>
					<view class="action-item" @click="deleteConversation">删除聊天</view>
				</view>
			</view>
		</scroll-view>

		<!-- 实名认证 -->
		<realname-modal :show="showRealnameModal" @close="showRealnameModal = false"
			@confirm="handleConfirm"></realname-modal>
	</view>
</template>

<script>
import {
	formatDate
} from '@/lib/utils';
import {
	getNoticecount
} from '@/common/api_user.js'
import {
	getPersonInfo
} from '@/common/api_meethuangshi.js'
import realnameModal from './realnameModal.vue'
export default {
	name: 'conversation',
	components: {
		realnameModal
	},
	data() {
		return {
			menuList: [{
				icon: 'icon1',
				name: '赞与收藏',
				count: 0,
				color: '#FF7891',
				path: '/pages/contacts/like'
			},
			{
				icon: 'icon2',
				name: '收到的评论',
				count: 0,
				color: '#FFA762',
				path: '/pages/contacts/comment'
			},
			{
				icon: 'icon3',
				name: '活动通知',
				count: 0,
				color: '#56D0C6',
				path: '/pages/contacts/msg'
			},
			{
				icon: 'icon4',
				name: '新增喜欢',
				count: 0,
				color: '#B176F2',
				path: `/subpage/meethuangshi/likeme?type=${0}&title=新增喜欢`
			}
			],
			unreadTotal: 0,
			conversations: [],
			actionPopup: {
				conversation: null,
				visible: false
			},
			currentUser: null,
			userProfile: {},
			showRealnameModal: false
		}
	},
	created() {
		if (this.hasLogin) {
			this.currentUser = this.userInfo;
			this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations); //监听会话列表变化
			this.loadConversations(); //加载会话列表
		}
		this.getNoticecount()
		this.getPersonInfo()
	},
	destroyed() {
		this.goEasy.im.off(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations);
	},
	methods: {
		formatDate,
		async getNoticecount() {
			const that = this
			const res = await getNoticecount()
			if (res.code == 200) {
				const {
					comment,
					likeCollection,
					notify
				} = res.data
				that.menuList = [{
					icon: 'icon1',
					name: '赞与收藏',
					count: likeCollection,
					color: '#FF7891',
					path: '/pages/contacts/like'
				},
				{
					icon: 'icon2',
					name: '收到的评论',
					count: comment,
					color: '#FFA762',
					path: '/pages/contacts/comment'
				},
				{
					icon: 'icon3',
					name: '活动通知',
					count: notify,
					color: '#56D0C6',
					path: '/pages/contacts/msg'
				},
				{
					icon: 'icon4',
					name: '新增喜欢',
					count: notify,
					color: '#B176F2',
					path: `/subpage/meethuangshi/likeme?type=${0}&title=新增喜欢`
				}
				]
			}
		},
		// 加载最新的会话列表
		loadConversations() {
			this.goEasy.im.latestConversations({
				onSuccess: (result) => {
					console.log(result, 'result');
					uni.hideLoading();
					let content = result.content;
					console.log(content, 'content')
					this.renderConversations(content);
				},
				onFailed: (error) => {
					uni.hideLoading();
					console.log('获取最新会话列表失败, error:', error);
				}
			});
		},
		renderConversations(content) {
			console.log(content, 'content');
			this.conversations = content.conversations;
		},
		topConversation() { //会话置顶
			this.actionPopup.visible = false;
			let conversation = this.actionPopup.conversation;
			let description = conversation.top ? '取消置顶' : '置顶';
			this.goEasy.im.topConversation({
				conversation: conversation,
				top: !conversation.top,
				onSuccess: function () {
					uni.showToast({
						title: description + '成功',
						icon: 'none'
					});
				},
				onFailed: function (error) {
					console.log(description, '失败：', error);
				}
			});
		},
		deleteConversation() {
			uni.showModal({
				content: '确认删除这条会话吗？',
				success: (res) => {
					if (res.confirm) {
						let conversation = this.actionPopup.conversation;
						this.actionPopup.visible = false;
						this.goEasy.im.removeConversation({
							conversation: conversation,
							onSuccess: function () {
								console.log('删除会话成功');
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							},
							onFailed: function (error) {
								console.log('删除会话失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							},
						});
					} else {
						this.actionPopup.visible = false;
					}
				},
			})
		},
		// 长按删除会话
		longPressDelete(conversation) {
			uni.showModal({
				title: '删除聊天记录',
				content: `确认删除与 ${conversation.data.name} 的聊天记录吗？`,
				confirmText: '删除',
				confirmColor: '#ff4757',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '删除中...'
						});
						this.goEasy.im.removeConversation({
							conversation: conversation,
							onSuccess: function () {
								uni.hideLoading();
								console.log('长按删除会话成功');
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							},
							onFailed: function (error) {
								uni.hideLoading();
								console.log('长按删除会话失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							},
						});
					}
				},
			});
		},
		chat(conversation) {
			console.log(conversation, 'conversation')
			if (this.userProfile.idCert === 2) {
				uni.navigateTo({
					url: `/subpage/meethuangshi/chat?id=${conversation.userId}&nickName=${conversation.data.name}&userAvatar=${conversation.data.avatar}`
				});
			} else {
				this.showRealnameModal = true
			}
		},
		showAction(conversation) {
			this.actionPopup.conversation = conversation;
			this.actionPopup.visible = true;
		},
		async getPersonInfo() {
			const userId = await this.getUserId()
			if (!userId) {
				console.log('用户信息获取失败或用户未登录')
				return
			}
			const res = await getPersonInfo({
				userId: userId
			})
			this.userProfile = res.data
		},
		handleConfirm() {
			this.showRealnameModal = false
			uni.navigateTo({
				url: `/subpage/meethuangshi/acceptAuth?isUpdate=true`
			});
		},
	}
}
</script>

<style lang="scss">
page {
	height: 100%;
	background-color: #F7F6FF;
}

.menu-item {
	.icon {
		width: 90rpx;
		height: 90rpx;
		border: 8rpx solid #fff;

		image {
			width: 90rpx;
			height: 90rpx;
		}

		.count {
			position: absolute;
			top: -20rpx;
			right: -20rpx;
			line-height: 40rpx;
			height: 40rpx;
			min-width: 40rpx;
			text-align: center;
			color: #34314F;
			background-color: #FFDE6D;
			border-radius: 30rpx;
		}
	}
}

.conversations {
	width: 750rpx;
	overflow-x: hidden;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	height: 100%;
}

.conversations .scroll-item {
	height: 152rpx;
	display: flex;
	align-items: center;
	padding-left: 32rpx;
}

.conversations .scroll-item .head-icon {
	width: 100rpx;
	height: 100rpx;
	border: 8rpx solid #fff;
	border-radius: 50% 50% 50% 10rpx;
	margin-right: 28rpx;
}

.conversations .scroll-item_info {
	height: 151rpx;
	width: 590rpx;
	padding-right: 32rpx;
	box-sizing: border-box;
	border-bottom: 1px solid #EFEFEF;
}

.conversations .scroll-item_info .item-info-top {
	padding-top: 20rpx;
	height: 60rpx;
	line-height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;

}

.conversations .item-info-top_name {
	font-size: 34rpx;
	color: #262628;
}

.conversations .item-info-top_time {
	font-size: 26rpx;
	color: rgba(179, 179, 179, 0.8);
	font-family: Source Han Sans CN;
}

.conversations .item-info-bottom {
	height: 40rpx;
	line-height: 40rpx;
	overflow: hidden;
}

.conversations .item-info-bottom-item {
	display: flex;
	justify-content: space-between;
}

.item-info-bottom .item-info-top_content {
	font-size: 30rpx;
	color: #b3b3b3;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;

}

.item-info-bottom .item-info-bottom_action {
	width: 50rpx;
	height: 50rpx;
	font-size: 20rpx;
	/* background: url("@/static/images/action.png") no-repeat center; */
	background-size: 28rpx 30rpx;
}

.no-conversation {
	width: 100%;
	text-align: center;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #9D9D9D;
}

.item-head {
	position: relative;
}

.item-head .item-head_unread {
	padding: 6rpx;
	background-color: #FFDE6D;
	color: #FFFFFF;
	font-size: 24rpx;
	line-height: 28rpx;
	border-radius: 24rpx;
	min-width: 24rpx;
	min-height: 24rpx;
	text-align: center;
	position: absolute;
	top: 0;
	right: 15rpx;
}

.action-container {
	width: 100%;
	height: 100%;
	position: fixed;
	top: 0;
	left: 0;
	display: flex;
	justify-content: center;
	align-items: center;
}

.action-container .layer {
	position: absolute;
	top: 0;
	left: 0;
	background: rgba(51, 51, 51, 0.5);
	width: 100%;
	height: 100%;
	z-index: 99;
}

.action-box {
	width: 400rpx;
	height: 240rpx;
	background: #ffffff;
	position: relative;
	z-index: 100;
	border-radius: 20rpx;
	overflow: hidden;
}

.action-item {
	text-align: center;
	line-height: 120rpx;
	font-size: 34rpx;
	color: #262628;
	border-bottom: 1px solid #EFEFEF;
}

.unread-text {
	color: #d02129;
}
</style>